package com.whut.mobilesafe.activity;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Formatter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.whut.mobilesafe.R;
import com.whut.mobilesafe.domain.ProcessInfo;
import com.whut.mobilesafe.engine.ProcessInfoProvider;
import com.whut.mobilesafe.utils.PrefUtils;
import com.whut.mobilesafe.viewholder.HeaderHolder;
import com.whut.mobilesafe.viewholder.ListItemProcessinfoHolder;

import java.util.ArrayList;

/**
 * 作    者:yubo.xiaoyubo
 * 时    间：2015/12/29 15:46
 * 版    本：1.0
 * 描    述：
 */
public class ProcessManageActivity extends Activity {

    private TextView tvRunningProcess;
    private TextView tvMemoryInfo;
    private ListView lvRoot;
    private Button btnAll;
    private Button btnReselect;
    private Button btnClean;
    private Button btnSetting;
    private TextView tvHeader;
    private LinearLayout llLoading;

    private ArrayList<ProcessInfo> mRunningProcessInfo;
    private DataAdapter mDataAdapter;
    private ArrayList<ProcessInfo> mUserProcessInfo;
    private ArrayList<ProcessInfo> mSystemProcessInfo;

    private CheckBox cbCheck;
    private long mTotalMem;
    private long mAvailMem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_process_manager);

        tvRunningProcess = (TextView) findViewById(R.id.tv_running_process);
        tvMemoryInfo = (TextView) findViewById(R.id.tv_memory_info);
        lvRoot = (ListView) findViewById(R.id.lv_root);
        btnAll = (Button) findViewById(R.id.btn_all);
        btnReselect = (Button) findViewById(R.id.btn_reselect);
        btnClean = (Button) findViewById(R.id.btn_clean);
        btnSetting = (Button) findViewById(R.id.btn_setting);
        tvHeader = (TextView) findViewById(R.id.tv_header);
        llLoading = (LinearLayout) findViewById(R.id.ll_loading);

        //获取当前正在运行的进程的个数
        setRunningProcessCount();
        //获取内存信息
        setMemoryInofo();

        //在滑动的时候判断如何当前位置是0就显示用户应用，否则就显示系统应用的个数
        lvRoot.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (mUserProcessInfo != null && mSystemProcessInfo != null) {
                    if (firstVisibleItem <= mUserProcessInfo.size()) {
                        tvHeader.setText("用户进程(" + mUserProcessInfo.size() + ")");
                    } else {
                        tvHeader.setText("系统进程(" + mSystemProcessInfo.size() + ")");
                    }
                }
            }
        });

        lvRoot.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ProcessInfo info = mDataAdapter.getItem(position);
                if (info != null) {
                    //表示获取到的是内容而不是标题栏
                    info.isChecked = !info.isChecked;
                    cbCheck = (CheckBox) view.findViewById(R.id.cb_check);
                    cbCheck.setChecked(info.isChecked);
                }
            }
        });

        initData();
    }

    //初始化数据
    private void initData() {
        new Thread() {

            @Override
            public void run() {
                llLoading.setVisibility(View.VISIBLE);
                mUserProcessInfo = new ArrayList<ProcessInfo>();
                mSystemProcessInfo = new ArrayList<ProcessInfo>();
                mRunningProcessInfo = ProcessInfoProvider.getRunningProcessInfo(getApplicationContext());
                for (ProcessInfo info : mRunningProcessInfo) {
                    if (info.isUser()) {
                        mUserProcessInfo.add(info);
                    } else {
                        mSystemProcessInfo.add(info);
                    }

                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mDataAdapter = new DataAdapter();
                        lvRoot.setAdapter(mDataAdapter);
                        llLoading.setVisibility(View.INVISIBLE);
                    }
                });
            }
        }.start();

    }

    class DataAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            boolean systemProcess = PrefUtils.getBoolean("show_system_process", true, getApplicationContext());
            if (!systemProcess) {
                return mUserProcessInfo.size() + 1;
            } else {
                return mUserProcessInfo.size() + mSystemProcessInfo.size() + 2;
            }
        }

        @Override
        public ProcessInfo getItem(int position) {
            if (position == 0 || position == mUserProcessInfo.size() + 1) {
                return null;//返回标签类型
            } else {
                //返回普通类型
                if (position < mUserProcessInfo.size() + 1) {
                    return mUserProcessInfo.get(position - 1);
                } else {
                    return mSystemProcessInfo.get(position - mUserProcessInfo.size() - 2);
                }
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemViewType(int position) {
            if (position == 0 || position == mUserProcessInfo.size() + 1) {
                return 0;
            } else {
                return 1;
            }
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            int type = getItemViewType(position);
            switch (type) {
                case 0:
                    HeaderHolder headerHolder = null;
                    if (convertView == null) {
                        headerHolder = new HeaderHolder();
                        convertView = View.inflate(getApplicationContext(), R.layout.list_item_header, null);
                        headerHolder.tvHeader = (TextView) convertView.findViewById(R.id.tv_header);

                        convertView.setTag(headerHolder);
                    } else {
                        headerHolder = (HeaderHolder) convertView.getTag();
                    }

                    if (position == 0) {
                        headerHolder.tvHeader.setText("用户进程(" + mUserProcessInfo.size() + ")");
                    } else {
                        headerHolder.tvHeader.setText("系统进程(" + mSystemProcessInfo.size() + ")");
                    }

                    break;

                case 1:
                    ListItemProcessinfoHolder appHolder = null;
                    if (convertView == null) {
                        appHolder = new ListItemProcessinfoHolder();
                        convertView = View.inflate(getApplicationContext(), R.layout.list_item_processinfo, null);

                        appHolder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
                        appHolder.tvSize = (TextView) convertView.findViewById(R.id.tv_size);
                        appHolder.ivIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
                        appHolder.cbCheck = (CheckBox) convertView.findViewById(R.id.cb_check);

                        convertView.setTag(appHolder);
                    } else {
                        appHolder = (ListItemProcessinfoHolder) convertView.getTag();
                    }
                    ProcessInfo info = getItem(position);
                    appHolder.tvSize.setText(info.getSize());
                    appHolder.tvName.setText(info.getName());
                    appHolder.ivIcon.setImageDrawable(info.getIcon());
                    appHolder.cbCheck.setChecked(info.isChecked);
                    break;
            }
            return convertView;
        }
    }


    private void setRunningProcessCount() {
        tvRunningProcess.setText("运行中的进程：" + ProcessInfoProvider.getRunningProcessCount(this) + "个");
    }


    public void setMemoryInofo() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memoryinfo = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(memoryinfo);

        mTotalMem = memoryinfo.totalMem;
        String totalMemStr = Formatter.formatFileSize(this, mTotalMem);


        mAvailMem = memoryinfo.availMem;
        String availMemStr = Formatter.formatFileSize(this, mAvailMem);
        tvMemoryInfo.setText("剩余/总内存:" + availMemStr + "/" + totalMemStr);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    //表示全选
    public void btnSelectAll(View view) {
        for (ProcessInfo info : mUserProcessInfo) {
            info.isChecked = true;
        }
        boolean showSystemProcess = PrefUtils.getBoolean("show_system_process", true, this);
        if (showSystemProcess) {
            for (ProcessInfo info : mSystemProcessInfo) {
                info.isChecked = true;
            }
        }
        mDataAdapter.notifyDataSetChanged();
    }

    //表示反选
    public void btnReSelect(View view) {
        for (ProcessInfo info : mUserProcessInfo) {
            info.isChecked = !info.isChecked;
        }
        boolean showSystemProcess = PrefUtils.getBoolean("show_system_process", true, this);
        if (showSystemProcess) {
            for (ProcessInfo info : mSystemProcessInfo) {
                info.isChecked = !info.isChecked;
            }
        }

        mDataAdapter.notifyDataSetChanged();
    }

    //表示一键清理
    public void btnClear(View view) {
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        // 被清理的进程集合
        ArrayList<ProcessInfo> killedList = new ArrayList<ProcessInfo>();
        //将用户集合总需要被清理的数据放入到killList中
        for (ProcessInfo info : mUserProcessInfo) {
            if (info.isChecked) {
                activityManager.killBackgroundProcesses(info.getName());
                killedList.add(info);
            }
        }
        boolean showSystemProcess = PrefUtils.getBoolean("show_system_process", true, this);
        if (showSystemProcess) {
            //如果显示系统进程就需要清理
            for (ProcessInfo info : mSystemProcessInfo) {
                if (info.isChecked) {
                    activityManager.killBackgroundProcesses(info.getName());
                    killedList.add(info);
                }
            }
        }
        long saveMemory = 0;
        for (ProcessInfo info : killedList) {
            if (info.isUser()) {
                mUserProcessInfo.remove(info);
            } else {
                mSystemProcessInfo.remove(info);
            }
            saveMemory += info.memory;
        }
        //文本显示
        Toast.makeText(this, "清理结束,帮您杀死" + killedList.size() + "个进程,共节省" +
                Formatter.formatFileSize(getApplicationContext(), saveMemory) +
                "空间", Toast.LENGTH_SHORT).show();

        mDataAdapter.notifyDataSetChanged();

        //更新剩余空间大小,其实根本没有杀掉嘛
        int runningNum = ProcessInfoProvider.getRunningProcessCount(this) - killedList.size();
        mAvailMem += saveMemory;
        tvRunningProcess.setText("运行中的进程：" + runningNum + "个");
        tvMemoryInfo.setText("剩余/总内存:" + Formatter.formatFileSize(this, mAvailMem) + "/" + Formatter.formatFileSize(this, mTotalMem));
    }

    //表示设置
    public void btnSetting(View view) {
        Intent intent = new Intent(this, ProcessSettingActivity.class);
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mDataAdapter.notifyDataSetChanged();
    }
}
